<template>
  <div class="hostel">
    <div class="search" v-if="user.position === 2 || user.position === 1">
      业主：
      <el-input
        style="width: 145px; padding-right:10px"
        placeholder="请输入业主"
        prefix-icon="el-icon-search"
        v-model="searchData.username">
      </el-input>

      <el-button style=" float: right; margin-left:10px;" @click="reset">重置</el-button>
      <el-button style=" float: right;" type="primary" @click="onSubmit">查询</el-button>
    </div>

    <div class="do" v-if="user.position === 2 || user.position === 0">
      <el-button @click="batchDelete()">批量删除</el-button>
    </div>

    <el-table
    ref="multipleTable"
    :data="tableData"
    tooltip-effect="dark"
    style="width: 100%"
    stripe
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="id"
      label="缴费单号">
    </el-table-column>
    <el-table-column
      prop="price"
      label="缴纳费用">
    </el-table-column>
    <el-table-column
      prop="type"
      label="费用类型">
    </el-table-column>
    <el-table-column
      prop="month"
      label="月份"
      :filters="[{ text: '1', value:'1' }, { text: '2', value:'2' }, { text: '3', value:'3' }, { text: '4', value:'4' }, { text: '5', value:'5' }
      , { text: '6', value:'6' }, { text: '7', value:'7' }, { text: '8', value:'8' }, { text: '9', value:'9' }, { text: '10', value:'10' }, { text: '11', value:'11' }
      , { text: '12', value:'12' }]"
      :filter-method="filterMonth"
      filter-placement="bottom-end">
      <template slot-scope="scope">
          {{scope.row.month}}
      </template>
    </el-table-column>
    <el-table-column
      prop="status"
      label="缴费状态"
      :filters="[{ text: '未缴纳', value: 0 }, { text: '已缴纳', value: 1 }]"
      :filter-method="filterTag"
      filter-placement="bottom-end">
      <template slot-scope="scope">
          <el-tag
          :type="scope.row.status === 0 ? 'primary' : 'success'"
          disable-transitions>{{getStatusText(scope.row.status)}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column
      prop="remark"
      label="备注">
      <template #default="scope">
        <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
          <span>{{ String(scope.row.remark).length > 10? String(scope.row.remark).substring(0, 10) + '......' : scope.row.remark }}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column
      prop="username"
      label="业主">
    </el-table-column>
    <el-table-column
      prop="createTime"
      label="生成时间">
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          v-if="user.position === 2 || user.id === scope.row.userId"
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>

          <el-button
          v-if="(user.position === 2 || user.position === 1)&& scope.row.status === 0"
          size="mini"
          type="warn"
          @click="urgeCost(scope.row)"
          >催缴</el-button>

          <el-button
          v-if="user.id === scope.row.userId && scope.row.status === 0"
          size="mini"
          type="success"
          @click="pay(scope.row)"
          >支付</el-button>
      </template>
    </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 20px; text-align: right; margin-right: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import api from '@/api';
import HostelFormPop from './HostelFormPop.vue';
import { mapState,mapMutations } from "vuex"

export default {
    computed:{
      ...mapState("login",["user"])
    },
    data() {
      return {
        userOptions:[],
        currentPage: 1,
        total:100,
        pageSize:10,
        options:[],
        searchData:{
          userId:"",
          pageNow: 1,
        },
        tableData: [{
          id:'',
          username:"",
          hostelId: '',
          userId: '',
          type:'水费',
          status: 0,
          price:'100', 
          remark:"",
          createdTime:"",
          month:"",
        }],
        selectedRow:[],
      }
    },
    methods: {
      //支付
      pay(row){
          if(!row.id || !row.price){
            return
          }
          api.apiPay(row.id,row.price,1).then(res =>{
                  // 创建一个新的窗口，并写入返回的 HTML 表单
                let newWindow = window.open();
                newWindow.document.open();
                newWindow.document.write(res);
                newWindow.document.close();
          }).catch(error => {
            console.error("支付请求失败:", error);
          });
        },

      getStatusText(status){
          switch(status){
            case 0 : return '未缴纳';
            case 1 : return '已缴纳';
            default : return '';
          }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
         this.searchData.pageNow = val
         //获取房屋信息
         this.onSubmit();
      },
      handleSelectionChange(selection) {
          this.selectedRow = selection
      },
      //催缴
      urgeCost(row){
        if(this.user.position !== 2 && this.user.position !==1){
          this.$message.error("权限不足")
          return
        }
        console.log(row)
        api.urgeCost(row).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              this.$message.success(res.data.message)
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      handleDelete(index, row) {
        if(row.status === 0){
          this.$message.error("该记录未缴费")
          return
        }
        this.tableData.splice(index,1)
        api.deleteCost(row.id).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              this.$message.success('删除成功')
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      filterMonth(value, row){
        return row.month === value;
      },
      filterTag(value, row) {
        return row.status === value;
      },
      //批量删除
      batchDelete(){
        var deleteIds = '';
        var float = false;
        this.selectedRow.map(item =>{
          if(deleteIds === ''){
            deleteIds = item.id
          }else{
            deleteIds = deleteIds + "," + item.id
          }
          if(!item.status||item.status ===0){
            float = true;
          }
        })
        if(float){
          this.$message.error("存在未缴费记录")
          return
        }

        if(deleteIds === ''){
          this.$message.error("请勾选删除项")
          return;
        }
        api.deleteCost(deleteIds).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              this.$message.success('删除成功');
              this.selectedRow.map(item =>{
                const index = this.tableData.findIndex((data) => data.id === item.id);
                this.tableData.splice(index,1)
              })
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      onSubmit() {
        //获取缴费信息
        api.costList(this.searchData).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              let noticeInfoDTO = res.data.data.costInfos

              const userOptionsMap = this.userOptions.reduce((map, option) => {
                    map[option.value] = option.label;
                    return map;
                }, {});
                noticeInfoDTO.forEach(item => {
                    if(item.userId){
                        const username = userOptionsMap[item.userId];
                        item.username = username;
                    }
              });
              if(this.searchData.username){
                noticeInfoDTO = noticeInfoDTO.filter(cost => {
                  var username = cost.username
                  return username.includes(this.searchData.username);
                })
              }
              this.tableData = noticeInfoDTO
              this.total = res.data.data.total
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      // 重置
      reset(){
        this.searchData.username = '',
        this.onSubmit();
      },
      //查询用户信息
      getUserInfo(){
        return new Promise((resolve, reject) => {
            api.getUserByPosition(false,false,{}).then(res => {
                  if (res.type === 'error') {
                    this.$message.error(res.message);
                    reject(res.message);
                  } else if (res.data.code === 200) {
                    const userList = res.data.data.userList;
                    this.userOptions = userList.map(item => ({
                      value: item.id,
                      label: item.username
                    }));
                    resolve();
                  } else {
                    this.$message.error(res.data.message);
                    reject(res.data.message);
                  }
            });
        }
      )}
    },
    created () {
      //获取房屋信息
      this.getUserInfo().then(() => {
        this.onSubmit();
      });
    },
}
</script>
<style scoped>
.hostel{
  background-color: #fff;
}
.hostel .search{
  padding: 10px;
}
.hostel .do{
  padding: 10px;
}
/* 自定义遮罩层样式 */
.hostel .houseFormPop {
  background-color: rgba(0, 0, 0, 0.5); /* 遮罩层颜色 */
  z-index: 9999; /* 设置一个较高的 z-index 使遮罩层位于最上层 */
}
</style>